package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Controller
public class MultipartFileController {

    @GetMapping("/form_layouts")
    public String form_layouts() {
        return "form/form_layouts";
    }

    @PostMapping("/upload")
    public String multipart(@RequestParam("email") String email,
                            @RequestParam("password") String password,
                            @RequestPart("headImg") MultipartFile headImg,
                            @RequestPart("photos") MultipartFile[] photos) throws IOException {

        log.info("传入的数据为：email={}, password={}, headImg的大小={}, photo的个数={}"
        ,email, password, headImg.getSize(), photos.length);

        if (!headImg.isEmpty()) {
            String originalFilename = headImg.getOriginalFilename();
            headImg.transferTo(new File("E:\\a\\" + originalFilename));
        }

        if (photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("E:\\a\\" + originalFilename));
                }
            }
        }

        return "main";
    }
}
